const router = require('koa-router')()
const { register, login } = require('../controller/user');
const { errnoModel, successModel } = require('../res-model/index');

router.prefix('/api/user')

/**
 * @description 用户注册路由
 */
router.post('/register', async (ctx, next) => {
  const { username, password } = ctx.request.body;
  const newUser = await register(username, password);
  try {
    ctx.body = new successModel(newUser)
  } catch (err) {
    console.error(err);
    ctx.body = errnoModel(1001, `注册失败-${err.message}`);
  }
})
/**
 * @description 用户登录
 */
router.post('/login', async (ctx, next) => {
  const { username, password } = ctx.request.body
  const loginCheng = await login(username, password);
  if (loginCheng) {
    ctx.session.userInfor = { username }
    ctx.body = new successModel()
  } else {
    ctx.body = new errnoModel(1002, '登录失败')
  }
})
module.exports = router
